﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Godot.core;

namespace Godot.core.io
{
    public class ResourceLoader
    {
        private const int MAX_LOADERS = 64;

        private static ResourceFormatLoader[] _loaders = new ResourceFormatLoader[MAX_LOADERS];
        private static int _loader_count = 0;

        public static void add_resource_format_loader(ResourceFormatLoader p_format_loader)
        {
            if (_loader_count >= MAX_LOADERS)
                return;
            _loaders[ _loader_count++ ] = p_format_loader;
        }

        public static Resource load(String p_path, String p_type_hint = "",  bool p_no_cache = false)
        {
            string local_path = Globals.singleton.localize_path(p_path);

	        local_path = find_complete_path(p_path,p_type_hint);
	        
            if(local_path == "") return null;

	        if (!p_no_cache && ResourceCache.has(local_path)) 
            {
		        //if (OS.singleton.is_stdout_verbose())
			    //    print_line("load resource: "+local_path+" (cached)");

		        return ResourceCache.get(local_path );
	        }

	        string remapped_path = PathRemap.singleton.get_remap(local_path);

	        //if (OS::get_singleton()->is_stdout_verbose())
		    //    print_line("load resource: ");

	        string extension = System.IO.Path.GetExtension(remapped_path);
	        bool found = false;
	
	        for (int i = 0; i < _loader_count; i++) 
            {
		
		        if (!_loaders[i].recognize(extension))
			        continue;

		        if (p_type_hint != "" && !_loaders[i].handles_type(p_type_hint))
			        continue;

		        found = true;
		        Resource res = _loaders[i].load(remapped_path, local_path);
		        if (res != null)
			        continue;

		        if (!p_no_cache)
			        res.set_path(local_path);

		        return res;
	        }

	        if (found) {
		        //ERR_EXPLAIN("Failed loading resource: "+p_path);
	        } else {
		        //ERR_EXPLAIN("No loader found for resource: "+p_path);
	        }
            return null;
        }

        public static string find_complete_path(string p_path, string p_type_hint)
        {
 	        throw new NotImplementedException();
        }   
    }
}
